package com.tools;

import java.util.Arrays;

/**
 * @author hua.huang JAVA加密
 */
class JavaCode {
	/***********************************************************
	 * @author sun.huang MSN:jxhuanghua@yahoo.com.cn
	 * @version time：2011-8-22 上午11:51:56
	 * @param ptr
	 * @param len
	 * @return CRC16加密
	 * @TODO
	 ***********************************************************/
	long cal_crc(byte[] ptr, int len) {
		int CRC16_POLY = 0x1021;
		int i, j;// word
		int value;// word
		int crc_ta[] = new int[256];// dword
		int k = 0;
		int crc;// dword
		byte da; // ubyte
		
		for (i = 0; i < 256; i++) {
			value = i << 8;
			for (j = 0; j < 8; j++) {
				if ((value & 0x8000) != 0) value = (((value << 1) & 0xffff) ^ CRC16_POLY);
				else value = ((value << 1) & 0xffff);
			}
			crc_ta[i] = value;
		}
		crc = 0;
		while (len-- != 0) {
			if (ptr[k] == '$') {
				char valid[] = new char[31];
				char flag[] = new char[31];
				flag[30] = 0;
				System.arraycopy("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$", 0, flag, 0, 30);
				System.arraycopy(ptr, k, valid, 0, 30);
				valid[30] = '\0';
				if (!Arrays.equals(valid, flag)) {
					k += 150;
					len -= 150;
				}
			}
			long temp = (crc >= 0 ? crc : (crc + 0xffffffffL + 1));
			da = (byte) ((temp / 256) & 0x000000FF);
			crc <<= 8; /* 左移8 位，相当于CRC 的低8 位乘以8 2 */
			int pos = (da ^ ptr[k]) & 0x000000FF;
			crc ^= crc_ta[pos]; /* 高8 位和当前字节相加后再查表求CRC ，再加上以前的 CRC */
			k++;
		}
		return (crc >= 0 ? crc : 0xffffffffL + crc + 1);
	}
	
}
